package com.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbs.config.BBSConfig;
import com.bbs.dto.PostAdd;
import com.bbs.dto.PostPreviewDto;
import com.bbs.dto.PostQuery;
import com.bbs.feign.UserClient;
import com.bbs.pojo.Comment;
import com.bbs.pojo.Post;
import com.bbs.mapper.PostMapper;
import com.bbs.pojo.Result;
import com.bbs.pojo.dto.UserDto;
import com.bbs.service.ICommentService;
import com.bbs.service.IPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bbs.service.SearchService;
import com.bbs.utils.ObjectUtil;
import com.bbs.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shardemachael
 * @since 2022-04-16
 */
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements IPostService {
    @Autowired
    private ICommentService commentService;
    @Autowired
    private SearchService searchService;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private UserClient userClient;

    @Override
    public Result<Object> addPost(PostAdd postAdd) throws Exception{
        Post post = new Post();
        ObjectUtil.mergeObj(postAdd, post);
        post.setUserId(SecurityUtil.getCurrentUser().getUserId());
        this.save(post);

        //加经验
        userClient.addExperience(SecurityUtil.getCurrentUser().getUserId(), BBSConfig.POST_EXPERIENCE);

        //同步双写-->搜索
        searchService.savePost(post);

        return Result.succeed();
    }

    @Override
    public IPage<PostPreviewDto> getPosts(PostQuery postQuery) {
        IPage<Post> postPage = null;
        if(postQuery.getSearchText() == null){
            //使用SQL按id、userId查询
            postPage = postMapper.selectPosts(new Page<>(postQuery.getPageNo(), postQuery.getPageSize()), postQuery);
        }else{
            //搜索search text
            postPage = searchService.searchPosts(postQuery.getSearchText(), (long)postQuery.getPageNo(), (long)postQuery.getPageSize());
        }
        List<Post> posts = (List<Post>) postPage.getRecords();

        List<PostPreviewDto> postPreviewDtos = posts.stream().map(this::postPreviewMap).collect(Collectors.toList());

        //获取发帖者用户信息
        Map<String, UserDto> userDtoMap = new HashMap<>();
        for (PostPreviewDto postPreviewDto : postPreviewDtos) {
            String userId = postPreviewDto.getUserId();
            UserDto user = userDtoMap.get(userId);
            if(user == null){
                Result<UserDto> result = userClient.getUser(userId);
                if(result != null){
                    user = result.getData();
                    userDtoMap.put(userId, user);
                }
            }

            postPreviewDto.setUser(user);
        }


        IPage<PostPreviewDto> postPreviewDtoPage = new Page<>();
        postPreviewDtoPage.setPages(postPage.getPages());
        postPreviewDtoPage.setCurrent(postPage.getCurrent());
        postPreviewDtoPage.setRecords(postPreviewDtos);
        postPreviewDtoPage.setSize(postPage.getSize());
        postPreviewDtoPage.setTotal(postPage.getTotal());

        return postPreviewDtoPage;
    }

    private PostPreviewDto postPreviewMap(Post post){
        PostPreviewDto postPreviewDto = new PostPreviewDto();
        postPreviewDto.setPostId(post.getPostId());
        postPreviewDto.setUserId(post.getUserId());
        postPreviewDto.setTitle(post.getTitle());
        postPreviewDto.setCreateTime(post.getCreateTime());

        //缩略的帖子内容
        final int MAX_CONTENT_LENGTH = 300;
        if(post.getContent().length() > MAX_CONTENT_LENGTH){
            postPreviewDto.setContent(post.getContent().substring(0, MAX_CONTENT_LENGTH) + "......");
        }else{
            postPreviewDto.setContent(post.getContent());
        }

        //查询帖子下回复数量
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("post_id", post.getPostId());
        queryWrapper.isNull("parent_id");
        long commentCount = commentService.count(queryWrapper);
        postPreviewDto.setCommentCount(commentCount);

        return postPreviewDto;
    }
}
